package Coursework;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class Util {
	public static final String FILE_NAME = "data";
	public void printMenu(){
		System.out.println();
		System.out.println("Please select a function:");
		System.out.println("1.Read a list of tasks from a text file.");
		System.out.println("2.Display, on screen, a list of all tasks.");
		System.out.println("3.Display, on screen, a list of all tasks ordered by priority and due today.");
		System.out.println("4.Add an item to the list.");
		System.out.println("5.Remove an item from the list.");
		System.out.println("6.Alter the priority or due date of a task.");
		System.out.println("7.Save all tasks to a text file.");
		System.out.println("8.Exit.");
		System.out.println();
	}
	
	public int getInt(Scanner scanner){
		int value = 0;
		try{
			value = Integer.parseInt(scanner.nextLine());
		}catch(Exception e){
			e.printStackTrace();
		}
		return value;
	}
	
	public Date getDate(Scanner scanner){
		Date date = null;
		try{
			date = new SimpleDateFormat("yyyy-MM-dd").parse(scanner.nextLine());
		}catch(Exception e){
		}
		return date;
	}
	
	public ToDoList getAllFromFile() throws IOException, ClassNotFoundException{
		FileInputStream fis = new FileInputStream(FILE_NAME);   
		ObjectInputStream ois = new ObjectInputStream(fis);   
        Object object = ois.readObject(); 
        ois.close();
        return (ToDoList)object;
	}
	
	public void saveToFile(ToDoList list) throws IOException{
		FileOutputStream fos = new FileOutputStream(FILE_NAME);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(list);
		oos.close();
	}
	
	public ToDoListItem getAnItem(Scanner scanner){
		try{
			System.out.print("Please input item's content : ");
			String content = scanner.nextLine();
			System.out.print("Please input item's priority : ");
			int priority = Integer.parseInt(scanner.nextLine());
			System.out.print("Please input item's due date(yyyy-MM-dd) : ");
			Date date = new SimpleDateFormat("yyyy-MM-dd").parse(scanner.nextLine());
			return new ToDoListItem(content,priority,date);
		}catch(Exception e){
			return null;
		}
	}
}
